<?php
namespace Modules\Activity\Http\Controllers\Admin\YiFanShang;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\YiFanShang\Room;
use \Modules\Activity\Entities\YiFanShang\Sku;
use \Modules\Activity\Entities\YiFanShang\Activity;

use Validator;
use ThrowException;
use Auth;
use DB;

// 概率编辑
class OddsController extends Controller
{
    // 房间设置的概率列表
    public function index(Request $req)
    {
        $rule = [
            'room_id' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $room = Room::getEntity([
            'id' => $req->room_id
        ]);

        $activity = $room->activity;

        $skuList = $activity->skus->toArray();

        $skuOptions = $room->sku_options;

        foreach ($skuList as $key => $item) {
            $skuList[$key]['target_index'] = @$skuOptions[$item['id']]['target_index'];
            $skuList[$key]['target_phone'] = @$skuOptions[$item['id']]['target_phone'];
        }

        return [
            'list'  => $skuList
        ];

    }

    // 保存概率设置
    public  function update(Request $req)
    {
        $rule = [
            'room_id' => ['required'],
            'list' => ['required']
        ];


        // 房间
        $room = Room::getEntity([
            'id' => $req->room_id
        ]);
        $skuOptions = $room->sku_options;

        $list = $req->input('list');
        $targetIndex = [];
        foreach ($list as $item) {
            $tempIndex = [];
            if ($item['shang_type'] === 0) {
                $arr = explode(' ', @$item['target_index'] ?: '');
                foreach ($arr as $num) {
                    if ($num) {
                        if (in_array($num, $targetIndex)) {
                            ThrowException::Conflict('序号' . $num . '重复出现');
                        }
                        array_push($targetIndex, $num);
                        array_push($tempIndex, $num);
                    }
                }

                if (count($tempIndex) > @$item['total_per_room']) {
                    ThrowException::Conflict(@$item['shang_title'] . '设置个数超出总发数');
                }
            }
            else {
                $arr = explode(' ', @$item['target_phone'] ?: '');
                foreach ($arr as $phone) {
                    if ($phone) {
                        if (strlen($phone) != 11) {
                            ThrowException::Conflict('购买赏限制需要填写11位手机号, ' . $phone . '不是手机号');
                        }
                    }
                }
            }

            $skuOptions[$item['id']]['target_index'] = @$item['target_index'];
            $skuOptions[$item['id']]['target_phone'] = @$item['target_phone'];
        }

        // 房间
        $room->update([
            'sku_options' => $skuOptions
        ]); 

        \Log::error($skuOptions);

        return [];
    }
}
